<template>
  <div>
    <div class="section-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="openAddDialog">添加用户</el-button>
    </div>

    <el-table :data="users" style="width: 100%; margin-top: 16px;">
      <el-table-column prop="Username" label="用户名" />
      <el-table-column prop="Role" label="角色">
        <template #default="scope">
          <el-select v-model="scope.row.Role" placeholder="选择角色" size="small" @change="updateUserRole(scope.row)">
            <el-option label="用户" value="user" />
            <el-option label="员工" value="staff" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="danger" @click="deleteUser(scope.row.UserID)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="添加用户">
      <el-form :model="form" label-width="80px">
        <el-form-item label="用户名"><el-input v-model="form.Username" /></el-form-item>
        <el-form-item label="邮箱"><el-input v-model="form.Email" /></el-form-item>
        <el-form-item label="密码"><el-input v-model="form.PasswordHash" type="password" show-password /></el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.Role">
            <el-option label="用户" value="user" />
            <el-option label="员工" value="staff" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import http from '@/utils/http' // 假设你有一个封装好的 axios 实例

const users = ref([])
const dialogVisible = ref(false)
const form = ref({
  Username: '',
  Email: '',
  PasswordHash: '',
  Role: 'user'
})

// 获取用户列表
async function fetchUsers() {
  const res = await http.get('/auth/admin/')
  users.value = res.data
}
onMounted(fetchUsers)

// 打开添加弹窗
function openAddDialog() {
  form.value = {
    Username: '',
    Email: '',
    PasswordHash: '',
    Role: 'user'
  }
  dialogVisible.value = true
}

// 保存用户（添加）
async function saveUser() {
  const res = await http.post('/auth/admin/', form.value)
  users.value.push(res.data) // 添加新用户到列表
  dialogVisible.value = false
}

// 更新用户角色
async function updateUserRole(user) {
  await http.put(`/auth/admin/${user.UserID}/`, user)
}

// 删除用户
async function deleteUser(id) {
  await http.delete(`/auth/admin/${id}/`)
  users.value = users.value.filter(u => u.UserID !== id)
}
</script>

<style scoped>
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>